import { Button } from "antd";
import {
  forwardRef,
  useEffect,
  useState,
  type HTMLProps,
  type PropsWithChildren,
  type ReactNode,
} from "react";
import Transition from "./Transition";
import XIcon from "@/assets/icons/x.svg?jsx";
import clsm from "@/lib/utils/clsm";

type FullSizeModalProps = PropsWithChildren<{
  visible: boolean;
  onClose: () => void;
  title?: ReactNode;
  fullscreen?: boolean;
  appear?: boolean;
  onClosed?: () => void;
}>;
export default function FullSizeModal(props: FullSizeModalProps) {
  const { visible, onClose, children, title, fullscreen, appear, onClosed } =
    props;

  return (
    <Transition
      show={visible}
      beforeEnterClass="opacity-0 scale-95"
      enteringClass="transition-all duration-300"
      leavingClass="transition-all duration-300"
      leftClass="opacity-0 scale-95"
      mountOnBody={fullscreen}
      appear={appear}
      onLeft={onClosed}
      unmountOnHide
    >
      <ZIndex
        className={clsm(
          "inset-0 flex flex-col bg-[#090909]",
          fullscreen ? "fixed" : "absolute",
        )}
      >
        <ModalHeader onCloseModal={onClose}>{title}</ModalHeader>
        <div className="min-h-0 flex-auto">{children}</div>
      </ZIndex>
    </Transition>
  );
}

type ModalHeaderProps = PropsWithChildren<{
  onCloseModal?: () => void;
}>;
function ModalHeader(props: ModalHeaderProps) {
  const { children, onCloseModal } = props;
  return (
    <div
      className={clsm(
        "relative flex flex-none justify-center py-3",
        children ? "border-b" : "h-10",
      )}
    >
      {children && <span>{children}</span>}
      <Button
        className="absolute right-1 top-1/2 -translate-y-1/2"
        type="text"
        onClick={onCloseModal}
      >
        <XIcon />
      </Button>
    </div>
  );
}

let _zIndex = 500;

const ZIndex = forwardRef<HTMLDivElement, HTMLProps<HTMLDivElement>>(
  function ZIndex(props, ref) {
    const { style, ...rest } = props;
    const [zIndex] = useState(_zIndex);
    useEffect(() => {
      _zIndex++;
      return () => {
        _zIndex--;
      };
    }, []);
    return <div style={{ zIndex, ...style }} {...rest} ref={ref} />;
  },
);
